package main

import (
	"fmt"
	"io"
	"net"
	"net/http"
	"strings"
)

/**
forward-proxy
*/

/**
代理结构体
*/
type Pxy struct{}

/**
代理结构体实现接口方法
*/
func (p *Pxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
	// 0、输出代理请求
	fmt.Printf("Received request: %s %s %s \n", req.Method, req.Host, req.RemoteAddr)

	// 1、建立连接池
	transport := http.DefaultTransport

	// 2、浅拷贝请求，并对其修改
	outReq := new(http.Request)
	*outReq = *req
	if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil {
		if piror, ok := outReq.Header["X-Forwarded-For"]; ok {
			clientIP = strings.Join(piror, ",") + "," + clientIP
		}
		outReq.Header.Set("X-Forwarded-For", clientIP)
	}

	// 3、请求下游
	res, err := transport.RoundTrip(outReq)
	if err != nil {
		rw.WriteHeader(http.StatusBadGateway)
		return
	}

	// 4、将下游内容返回给上游
	for key, value := range res.Header {
		for _, v := range value {
			rw.Header().Set(key, v)
		}
	}
	rw.WriteHeader(http.StatusOK)
	io.Copy(rw, res.Body)
	defer res.Body.Close()
}

func main() {
	fmt.Print("Serve Running On 8080 \n")
	http.Handle("/", &Pxy{})
	http.ListenAndServe(":8080", nil)
}
